package com.caojm.mptools.client.utils;


import java.sql.*;

public class DatabaseHelper {

    private static final String DB_URL = "jdbc:mysql://localhost:3306/mingpixel_tools";  // 数据库URL
    private static final String DB_USER = "root";  // 数据库用户名
    private static final String DB_PASSWORD = "your_password";  // 数据库密码

    public static Connection getConnection() throws SQLException {
        try {
            // 加载 MySQL 驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            return (Connection) DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        } catch (ClassNotFoundException | SQLException e) {
            throw new SQLException("数据库连接失败", e);
        }
    }

    // 将玩家和官网账户绑定信息存储到数据库
    public static boolean bindAccount(String playerName, String websiteAccount) {
        String sql = "INSERT INTO account_bindings (player_name, website_account) VALUES (?, ?)";

        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {

            // 设置参数
            statement.setString(1, playerName);
            statement.setString(2, websiteAccount);

            // 执行插入操作
            int rowsAffected = statement.executeUpdate();
            return rowsAffected > 0;  // 返回是否插入成功
        } catch (SQLException e) {
            e.printStackTrace();
            return false;  // 如果数据库操作失败，返回 false
        }
    }

    public static boolean unbindAccount(String playerName) {
        String sql = "DELETE FROM account_bindings WHERE player_name = ?";

        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {

            // 设置参数
            statement.setString(1, playerName);

            // 执行删除操作
            int rowsAffected = statement.executeUpdate();
            return rowsAffected > 0;  // 返回是否删除成功
        } catch (SQLException e) {
            e.printStackTrace();
            return false;  // 如果数据库操作失败，返回 false
        }
    }

    // 获取玩家绑定的官网账号
    public static String getAccount(String playerName) {
        String sql = "SELECT website_account FROM account_bindings WHERE player_name = ?";

        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {

            // 设置参数
            statement.setString(1, playerName);

            // 执行查询
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    return resultSet.getString("website_account");  // 返回绑定的官网账号
                } else {
                    return null;  // 如果没有找到绑定记录，返回 null
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;  // 如果数据库操作失败，返回 null
        }
    }


}
